package edu.arizona.arid.akshen.controller;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;

public final class NavigationController {
	
	public static final int maxStackHeight = 10;
	
	private MIDlet midlet;
	private Display display;
	
	private ViewController[] controllerStack = new ViewController[10];
	private int stackHeight = 0;
	
	public NavigationController(MIDlet midlet) {
		this.midlet = midlet;
	}
	
	public void setDisplay(Display display) {
		this.display = display;
	}

	public Display getDisplay() {
		return display;
	}
	
	/**
	 * Causes the previous view to be the current view as it pops the current
	 * view controller from the stack.
	 * 
	 * @return The current view controller
	 */
	public ViewController popViewController() {
		if(stackHeight < 2) {
			//throw new Exception("Empty view controller stack");
			System.err.println("Empty view Controller stack");
			return null;
		}
		stackHeight--;
		//System.out.println("Poping view controller, height = " + stackHeight);
		//System.out.println("Displayable = " + controllerStack[stackHeight-1].getDisplayable());
		ViewController controller = controllerStack[stackHeight];
		controller.viewWillDisappear();
		display.setCurrent(controllerStack[stackHeight-1].getDisplayable());
		controller.viewDidDisappear();
		
		return controller;
	}
	
	/**
	 * Causes the the main view of the given view controller to be the current
	 * view as it adds the given view controller on the top of the stack.
	 * 
	 * @param controller
	 */
	public void pushViewController(ViewController controller) {
		if(stackHeight >= maxStackHeight) {
			System.err.println("View controller stack is full");
			return;
		}
		
		controllerStack[stackHeight++] = controller;
		//System.out.println("Pusing view controller, height = " + stackHeight);
		//System.out.println("Displayable = " + controller.getDisplayable());
		controller.setNavigationController(this);
		controller.viewWillAppear();
		display.setCurrent(controller.getDisplayable());
		controller.viewDidAppear();
	}
	
	/**
	 * Displays the given alert.
	 * 
	 * @param alert
	 */
	public void displayAlert(Alert alert) {
		display.setCurrent(alert, controllerStack[stackHeight-1].getDisplayable());
	}
	
	public void pauseApp() {
		midlet.notifyPaused();
	}

	public void destroyApp() {
		midlet.notifyDestroyed();
	}
}
